package com.mysteel.cyx.demo.face.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.mysteel.cyx.demo.baomidou.entity.Department;
import com.mysteel.cyx.demo.baomidou.entity.User;
import com.mysteel.cyx.demo.baomidou.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 在mysql中 行级锁的释放是在事务提交之后才会释放，如果事务回滚，则行级锁不会释放，造成死锁。 因此，在业务场景中，需要注意避免死锁的发生
 *
 * @Author：cyx
 * @Date：2024/5/8 9:10
 */
@Service
public class CommonService {
    private Lock lock = new ReentrantLock();

    @Autowired
    private UserMapper userMapper;


    public void test() {
        try {
            //加锁
            lock.lock();
            // 业务逻辑
            test2();
        } finally {
            lock.unlock(); // 解锁
        }
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void test2() {
        // 简单的select + update 模拟业务场景
        User user = userMapper.selectById(6);

        // 实现 level -- 操作
        User updater = new User();
        updater.setId(6L);
        updater.setAge(user.getAge() - 1);
        userMapper.updateById(updater);
    }


    /**
     * 通用树形结构数据转换
     * rootId可能为NULL,也可能是1或者0
     * 注意:
     *  setIdKey的名称需要跟putExtra的名称一致,否则会报空指针
     *  setParentIdKey的名称需要跟putExtra的名称一致,否则会数据返回为null
     */
    public List<Tree<String>> testTree(List<Department> dataList, String rootId) {
        //2.配置
        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("departmentId");                              //默认id，可以不设置
        config.setParentIdKey("departmentParentId");                       //父id
        config.setNameKey("name");              //分类名称
        config.setDeep(3);                                  //最大递归深度
        config.setChildrenKey("childrenList");              //孩子节点
        config.setWeightKey("sort");                        //排序字段
        //转换器
        return TreeUtil.build(dataList, rootId, config,
                (treeNode, tree) -> {
//                    tree.setId(treeNode.getId().toString());
//                    tree.setParentId(treeNode.getParentId() == null ? "" : treeNode.getParentId().toString());
//                    tree.setName(treeNode.getName());
                    tree.putExtra("departmentId",treeNode.getId().toString());
                    tree.putExtra("departmentParentId",treeNode.getParentId() == null ? "" : treeNode.getParentId().toString());
                    tree.putExtra("departmentName",treeNode.getName());
                });

    }
}
